#!/usr/bin/env python
#coding=utf-8

import paramiko,cmd,sys

class RunCommand(cmd.Cmd):
	"""
	ssh脚本的升级版本，利用paramiko模块和cmd
	"""
	prompt = 'ssh => '

	def __init__(self):
		"""init command"""
		cmd.Cmd.__init__(self)
		self.hosts = []
		self.connections = []

	def do_add_host(self, args):
		"""
		批量添加主机
		参数格式: ip,user,pass
		"""
		if args:
			self.hosts.append(args.split(' '))
		else:
			print "usage: host,user,pass"

	def do_connect(self, args):
		"""批量连接"""
		self.connections = []
		#self.do_close()
		for host in self.hosts:
			client = paramiko.SSHClient()
			client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
			#连接host列表里的主机
			client.connect(host[0], 22, host[1], host[2])
			self.connections.append(client)
			print 'connect', host[0], 22, host[1], host[2]

	def do_run(self, cmd):
		"""run command on hosts"""
		if cmd:
			for host, conn in zip(self.hosts, self.connections):
				stdin, stdout, stderr = conn.exec_command(cmd)
				for line in stdout.readlines():
					print host[0], line.strip()
		else:
			print 'usage: input command.'

	def do_load_host(self, args):
		"""
		load hosts from host file
		"""
		with open(args) as f:
		#遍历文件，取出每一条记录加入到host列表中
			for i in f:
				i = i.strip()
				if not i: continue
				ip, username, password = i.split()[:3]
				self.hosts.append((ip, username, password))
				print '==========host list start==========='
			for ip, username, password in self.hosts:
				print ip, username, password
			print '===========host list end=========='

	def do_close(self, args):
		"""close all connections of hosts"""
		for conn in self.connections:
			conn.close()
			sys.exit()
		print 'byebye'

if __name__ == '__main__':
	RunCommand().cmdloop()